package com.heima.socket.udp.uniacst;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        /**
         * udp接收数据
         */

        // 1. 创建DatagramSocket对象
        // 接收时要绑定端口
        DatagramSocket ds = new DatagramSocket(10086);

        // 2. 接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        ds.receive(dp);

        // 3. 解析数据
        byte[] data = dp.getData();
        int len = dp.getLength();
        InetAddress address = dp.getAddress();
        int port = dp.getPort();

        System.out.println("接收到数据: " + new String(data, 0, len));
        System.out.println("该数据是从" + address + "的" + port + "端口发出的");

        // 4. 释放资源
        ds.close();
    }
}
